package com.tensquare.split.service;

import com.tensquare.split.dao.SpitDao;
import com.tensquare.split.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.Date;
import java.util.List;

/**
 * @author: create by  Raphaelkxy
 * @version: v1.0
 * @description: com.tensquare.split.service
 * @date:2019/9/11
 */
@Service
public class SplitService {

    @Autowired
    private SpitDao spitDao;


    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询全部记录
     */

    public List<Spit>findAll(){
        return spitDao.findAll();
    }

    /**
     * 根据主键查询实体
     */

    public Spit findById(String id){
        Spit split = spitDao.findById(id).get();
        return split;
    }

    /**
     * 增加
     */
    public void add(Spit split){
        split.set_id(idWorker.nextId()+"");//主键值
         split.setPublishtime(new Date());
         split.setVisits(0);
         split.setShare(0);
         split.setThumbup(0);
         split.setComment(0);
         split.setState(1);
         if(split.getParentid()!=null&&!"".equals(split.getParentid())){
             Query query = new Query();
             query.addCriteria(Criteria.where("_id").is(split.getParentid()));
             Update update = new Update();
             update.inc("comment",1);
             mongoTemplate.updateFirst(query,update,"spit");
         }
        spitDao.save(split);
    }
    /**
     * 修改
     */
    public void update(Spit split){
        spitDao.save(split);
    }
    /**
     * 删除
     */
    public void deleteById(String id){
        spitDao.deleteById(id);
    }

    /**
     * 根据上级ID查询吐槽列表
     */

    public Page<Spit>findByParent(String parentid,int page,int size){
        PageRequest pageRequest = PageRequest.of(page-1,size);
        return spitDao.findByParentid(parentid,pageRequest);
    }

    /*** 点赞 * @param id */
    public void updateThumbup(String id) {
//        Spit spit = spitDao.findById(id).get();
//        spit.setThumbup(spit.getThumbup() + 1);
//        spitDao.save(spit);
        //效率优化后
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.updateFirst(query, update, "spit");
    }

}
